package com.wunu.smartlock1.bluetooth.command

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import kotlin.experimental.and

/**
 * Created by peiwei on 2018/4/21.
 */

public class CheckBindCommand: IComand {
    override var header: Byte = 0xc1.toByte()
    override fun payload(): ByteArray {
        val byteArrayOutputStream = ByteArrayOutputStream()
        byteArrayOutputStream.write(0xaaaa)//报头
        byteArrayOutputStream.write(0xc0)//报文类型
        byteArrayOutputStream.write(0x00)//数据长度
        var sum = 0
        for (byte in byteArrayOutputStream.toByteArray()) {
            sum += byte
        }
        sum = sum.and(0xff)
        byteArrayOutputStream.write(sum)
        return byteArrayOutputStream.toByteArray()
    }

    override fun decode(byteArray: ByteArray): Map<String, Any> {
        val byteArrayInputStream = ByteArrayInputStream(byteArray)
        //读取mac地址
        val mac = byteArrayInputStream.readBytes(6)
        //读取状态
        val state = byteArrayInputStream.readBytes(1)
        val macStr = mac.reversed().joinToString(":")
        val state_ = state.toString() == "1"
        return mapOf("mac" to macStr, "state" to state_)
    }
}